package com.party.mobile.biz.file;

import com.party.api.dto.wechat.requst.XcxQrCodeRequest;
import com.party.api.service.wechat.IWechatService;
import com.party.common.constant.Constant;
import com.party.common.utils.StringUtils;
import com.party.core.service.cos.CosBizService;
import com.party.file.cos.dto.SearchResult;
import com.party.file.cos.dto.UploadResult;
import com.party.file.cos.meta.InsertOnly;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

@Service
public class FileBizService {
    /**
     * 上传到万象优图路径
     */
    @Value("#{party['upload.ci.path']}")
    private String uploadCIPath;

    @Autowired
    private CosBizService cosBizService;

    @Autowired
    private IWechatService wechatService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 读取流
     *
     * @param is
     * @return
     * @throws IOException
     */
    private byte[] readInputStream(InputStream is) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int len = 0;
        while ((len = is.read(data)) != -1) {
            outStream.write(data, 0, len);
        }
        is.close();
        return outStream.toByteArray();
    }


    public String getUploadCIPath(String memberId, String folderName) {
        String path = String.format(uploadCIPath, memberId, folderName);
        return path;
    }

    /**
     * 获取二维码路径（不带logo）
     *
     * @param cloudFileName 云文件名
     * @param cloudFilePath 云文件路径
     * @param insertOnly    是否覆盖
     * @param qrCodeRequest 生成小程序二维码请求参数
     * @return 二维码路径
     */
    private String uploadCloudInnerXcx(String cloudFileName, String cloudFilePath, Integer insertOnly,
                                       XcxQrCodeRequest qrCodeRequest, String accessToken) {
        cloudFileName = cloudFileName + ".jpg";
        cloudFilePath = "/" + cloudFilePath;
        try {
            // 目录操作结果
            Boolean result = false;
            // 检查文件是否存在
            String accessUrl = cosBizService.statFile(cloudFilePath + cloudFileName);
            if (StringUtils.isNotEmpty(accessUrl)) {
                // 不覆盖
                if (1 == insertOnly) {
                    return cosBizService.getPreviewPicUrl(accessUrl);
                    // 删除覆盖
                } else if (0 == insertOnly) {
                    result = true;
                }
            } else {
                // 检查目录是否存在
                SearchResult newSearchResult = cosBizService.statFolder(cloudFilePath);
                if (newSearchResult.getCode() == 0 && newSearchResult.getMessage().equals(Constant.WECHAT_SUCCESS)) {
                    // 目录存在，则不用去创建目录
                    result = true;
                } else {
                    // 创建目录结果
                    result = cosBizService.createFolder(cloudFilePath);
                }
            }
            if (result) {
                // 上传文件
                InputStream inputStream = wechatService.createMiniProgramQrCode(qrCodeRequest, accessToken);
                if (inputStream != null) {
                    byte[] bytes = readInputStream(inputStream);
                    String str = new String(bytes, "UTF-8");
                    if (str.indexOf("errcode") != -1) {
                        throw new Exception(str);
                    }
                    ByteArrayInputStream input = new ByteArrayInputStream(bytes);
                    UploadResult upload = cosBizService.uploadFile(input, cloudFilePath + cloudFileName, InsertOnly.NO_OVER_WRITE);
                    return cosBizService.getPreviewPicUrl(upload.getAccessUrl());
                }
            }
        } catch (Exception e) {
            logger.error("上传二维码到万象优图异常：cloudFilePath——"
                    + cloudFilePath + "；cloudFileName——" + cloudFileName, e);
        }
        return null;
    }

    /**
     * 上传到二维码到万象优图
     *
     * @param cloudFileName 云文件名
     * @param cloudFilePath 云目录
     * @param qrCodeRequest 生成二维码参数
     * @return
     */
    public String uploadCloudOut(String cloudFileName, String cloudFilePath,
                                 XcxQrCodeRequest qrCodeRequest, String accessToken, Integer insertOnley) {
        return this.uploadCloudInnerXcx(cloudFileName, cloudFilePath, insertOnley, qrCodeRequest, accessToken);
    }
}
